<template>
  <div class="app-container">
    <!-- 侧边栏 -->
    <div class="sidebar">
      <div class="sidebar-header">
        <h2 class="sidebar-title">在线教育平台</h2>
        <el-button icon="el-icon-menu" class="toggle-btn" @click="toggleSidebar"></el-button>
      </div>
      <el-menu
          :default-active="activeMenu"
          class="el-menu-vertical-demo"
          background-color="#0b1b33"
          text-color="#fff"
          active-text-color="#409EFF"
          :collapse="isSidebarCollapse"
          router
      >
        <el-menu-item index="/home">
          <el-icon><Menu /></el-icon>
          <span>课程管理</span>
        </el-menu-item>
        <el-menu-item index="/kgfl">
          <el-icon><Folder /></el-icon>
          <span>课程分类管理</span>
        </el-menu-item>
        <el-menu-item index="/stu">
          <el-icon><User /></el-icon>
          <span>学生管理</span>
        </el-menu-item>
        <el-menu-item index="/teacher">
          <el-icon><User /></el-icon>
          <span>教师管理</span>
        </el-menu-item>
        <el-menu-item index="/per">
          <el-icon><User /></el-icon>
          <span>个人中心</span>
        </el-menu-item>
      </el-menu>
    </div>

    <!-- 主内容区 -->
    <div class="main-content" :class="{ 'sidebar-collapse': isSidebarCollapse }">
      <!-- 面包屑（可根据实际需求调整） -->
      <el-breadcrumb separator="/" class="breadcrumb">
        <el-breadcrumb-item>课程分类管理</el-breadcrumb-item>
      </el-breadcrumb>

      <!-- 页面标题与操作 -->
      <div class="page-header">
        <h1 class="page-title">课程分类列表</h1>
        <el-button type="primary" @click="handleAddCategory">
          <el-icon><Plus /></el-icon>添加分类
        </el-button>
      </div>

      <!-- 搜索筛选区 -->
      <el-card class="search-card">
        <el-form :inline="true" :model="state.searchForm" class="search-form">
          <el-form-item label="搜索">
            <el-input v-model="state.searchForm.keyword" placeholder="请输入分类名称搜索" clearable />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">
              <el-icon><Search /></el-icon>搜索
            </el-button>
            <el-button @click="resetSearch">
              <el-icon><Refresh /></el-icon>重置
            </el-button>
          </el-form-item>
        </el-form>
      </el-card>

      <!-- 课程分类列表 -->
      <el-card class="course-category-list-card">
        <el-table
            :data="state.categoryList"
            border
            stripe
            highlight-current-row
            row-key="id"
        >
<!--          <el-table-column label="序号" type="index" width="60" />-->
          <el-table-column prop="id" label="分类ID" />
          <el-table-column prop="categoryName" label="分类名称"  />
          <el-table-column prop="categoryDescription" label="分类描述"  />
          <el-table-column prop="status" label="状态">
            <template #default="scope">
              <el-tag :type="scope.row.status === '启用' ? 'success' : 'info'">
                {{ scope.row.status }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200">
            <template #default="scope">
              <el-button type="info" size="small" @click="handleEditCategory(scope.row)">
                <el-icon><Edit /></el-icon>编辑
              </el-button>
              <el-button type="danger" size="small" @click="handleDeleteCategory(scope.row)">
                <el-icon><Delete /></el-icon>删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页组件 -->
        <div class="pagination-container">
          <el-pagination
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="state.currentPage"
              :page-sizes="[10, 20, 50, 100]"
              :page-size="state.pageSize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="state.total"
          />
        </div>
      </el-card>

      <!-- 添加/编辑课程分类对话框 -->
      <el-dialog
          :visible.sync="state.dialogVisible"
          title="课程分类信息"
          width="400px"
          :close-on-click-modal="false"
          :close-on-press-escape="false"
      >
        <template #content>
          <el-form :model="state.formData" ref="formRef" label-width="120px">
            <el-form-item
                label="分类名称"
                prop="name"
                :rules="{ required: true, message: '请输入分类名称', trigger: 'blur' }"
            >
              <el-input v-model="state.formData.name" placeholder="请输入分类名称" clearable />
            </el-form-item>
            <el-form-item label="分类状态" prop="status">
              <el-radio-group v-model="state.formData.status">
                <el-radio label="启用">启用</el-radio>
                <el-radio label="禁用">禁用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-form>
        </template>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="state.dialogVisible = false">取消</el-button>
            <el-button type="primary" @click="saveCategory">确定</el-button>
          </span>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script setup>
import {ref, reactive, onMounted, watch} from 'vue'
import {
  Plus,
  Search,
  Edit,
  Delete,
  Refresh,
  Menu,
  Folder,
  User
} from '@element-plus/icons-vue'
import {
  ElMessage,
  ElMessageBox,
  ElForm,
  ElTag,
  ElTable,
  ElTableColumn,
  ElDialog,
  ElFormItem,
  ElInput,
  ElRadio,
  ElRadioGroup,
  ElPagination,
  ElCard,
  ElBreadcrumb,
  ElBreadcrumbItem,
  ElButton
} from 'element-plus'
import request from "@/utils/request.js";

// 侧边栏相关状态
const isSidebarCollapse = ref(false)
const activeMenu = ref('course-category')
const toggleSidebar = () => {
  isSidebarCollapse.value = !isSidebarCollapse.value
}

// 课程分类管理相关状态
const state = reactive({
  categoryList: [], // 课程分类列表数据
  total: 0, // 总记录数
  currentPage: 1, // 当前页码
  pageSize: 10, // 每页显示数量
  searchForm: {
    keyword: '' // 搜索关键词
  },
  dialogVisible: false, // 对话框是否显示
  dialogTitle: '添加分类', // 对话框标题
  formData: {
    id: null,
    name: '',
    status: '启用'
  }
})

// 表单引用
const formRef = ref(null)
// 模拟获取课程分类列表数据（实际应替换为接口请求）
const fetchCategoryList = () => {
  // 这里模拟接口请求，实际开发中替换为真实的 API 调用
   setTimeout(() => {
     let mockData = [
       {
         id: 1,
         name: '前端开发',
         status: '启用',
         courseCount: 25
       },
       {
         id: 2,
         name: '后端开发',
         status: '启用',
         courseCount: 30
       },
       {
         id: 3,
         name: '移动开发',
         status: '禁用',
         courseCount: 15
       },
       {
         id: 4,
         name: '人工智能',
         status: '启用',
         courseCount: 20
       },
       {
         id: 5,
         name: '数据科学',
         status: '启用',
         courseCount: 18
       }
     ]
    // 模拟搜索过滤
     request('/course/findAll')
          .then(Response =>{
            mockData = Response.data;
            for (let i = 0; i < mockData.length; i++){
              if(mockData[i].status == "published") mockData[i].status = "启用"
              else mockData[i].status = "禁用"
            }
            // 应用搜索过滤
            if (state.searchForm.keyword) {
              const keyword = state.searchForm.keyword.toLowerCase()
              mockData = mockData.filter(item =>
                  item.name.toLowerCase().includes(keyword)
              )
            }
            // 应用分页
            const startIndex = (state.currentPage - 1) * state.pageSize
            const endIndex = startIndex + state.pageSize
            const paginatedData = mockData.slice(startIndex, endIndex)

            state.categoryList.splice(0, state.categoryList.length)
            state.categoryList.push(...paginatedData)
            state.total = mockData.length
          }, 300)
          })
}

onMounted(() => {
  fetchCategoryList()
})

// 搜索分类
const handleSearch = () => {
  state.currentPage = 1
  fetchCategoryList()
}

// 重置搜索条件
const resetSearch = () => {
  state.searchForm.keyword = ''
  state.currentPage = 1
  fetchCategoryList()
}

// 分页相关
const handleSizeChange = (newSize) => {
  state.pageSize = newSize
  fetchCategoryList()
}

const handleCurrentChange = (newPage) => {
  state.currentPage = newPage
  fetchCategoryList()
}

// 添加分类
const handleAddCategory = () => {
  // 重置表单数据
  state.formData.id = null
  state.formData.name = ''
  state.formData.status = '启用'
  state.dialogTitle = '添加分类'

  // 显示对话框
  state.dialogVisible = true
}

// 编辑分类
const handleEditCategory = (row) => {
  // 复制数据到表单
  state.formData.id = row.id
  state.formData.name = row.name
  state.formData.status = row.status
  state.dialogTitle = '编辑分类'

  // 显示对话框
  state.dialogVisible = true
}

// 删除分类
const handleDeleteCategory = (row) => {
  ElMessageBox.confirm(
      `确定要删除分类「${row.name}」吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
  ).then(() => {
    // 模拟删除接口请求
    setTimeout(() => {
      // 找到要删除的索引
      const index = state.categoryList.findIndex((item) => item.id === row.id)
      if (index !== -1) {
        // 从列表中移除
        state.categoryList.splice(index, 1)
        state.total--
        ElMessage.success('删除成功')
      }
    }, 300)
  })
}

// 保存分类（添加/编辑）
const saveCategory = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      // 验证分类名称是否已存在
      const isNameExists = state.categoryList.some(
          item => item.name === state.formData.name && item.id !== state.formData.id
      )

      if (isNameExists) {
        ElMessage.error('该分类名称已存在')
        return
      }

      if (state.formData.id) {
        // 编辑操作
        const index = state.categoryList.findIndex((item) => item.id === state.formData.id)
        if (index !== -1) {
          // 更新列表中的数据
          state.categoryList.splice(index, 1, {...state.formData})
          ElMessage.success('更新成功')
        }
      } else {
        // 新增操作
        state.formData.id = Date.now() // 简单模拟 ID 生成
        // 添加到列表
        state.categoryList.push({...state.formData})
        state.total++
        ElMessage.success('创建成功')
      }

      // 关闭对话框
      state.dialogVisible = false
    } else {
      ElMessage.error('请完善表单信息')
    }
  })
}

// 监听侧边栏折叠状态
watch(isSidebarCollapse, (newVal) => {
  // 可在此处添加侧边栏折叠后的额外逻辑
})
</script>

<style scoped>
.app-container {
  display: flex;
  height: 100vh;
  overflow: hidden;
}

/* 侧边栏样式 */
.sidebar {
  width: 220px;
  background-color: #0b1b33;
  color: #fff;
  transition: width 0.3s ease-in-out;
  display: flex;
  flex-direction: column;
}

.sidebar-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 15px 20px;
  border-bottom: 1px solid #1f334b;
}

.sidebar-title {
  font-size: 18px;
  font-weight: 600;
  margin: 0;
}

.toggle-btn {
  background: transparent;
  border: none;
  color: #fff;
  cursor: pointer;
  font-size: 20px;
}

.el-menu-vertical-demo {
  border-right: none;
}

/* 主内容区样式 */
.main-content {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
  transition: margin-left 0.3s ease-in-out;
}

.sidebar-collapse {
  margin-left: 64px; /* 侧边栏折叠后，主内容区调整左边距 */
}

/* 面包屑样式 */
.breadcrumb {
  margin-bottom: 10px;
}

/* 页面标题与操作样式 */
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-title {
  font-size: 24px;
  font-weight: 600;
  color: #303133;
  margin: 0;
}

/* 搜索卡片样式 */
.search-card {
  margin-bottom: 20px;
}

.search-form {
  display: flex;
  align-items: center;
}

/* 课程分类列表卡片样式 */
.course-category-list-card {
  margin-bottom: 20px;
}

/* 分页样式 */
.pagination-container {
  margin-top: 20px;
  text-align: right;
}

/* 对话框样式 */
.dialog-footer {
  text-align: right;
}
</style>
